<template>
  <div class="portraitRepaint-containter">
    <div class="input-containter">
      <div class="input">
        <el-upload
          class="upload-demo"
          drag
          action="host"
          multiple
          name="file"
          :before-upload="handleBeforeUpload"
          :headers="headers"
        >
          <el-icon class="el-icon--upload"><upload-filled /></el-icon>
          <div class="el-upload__text">
            拖拽文件到这里或者 <em>点击上传文件</em>
          </div>
          <template #tip>
            <div class="el-upload__tip">文件小于500kb,格式为jpg/png</div>
          </template>
        </el-upload>
      </div>
      <div class="input">
        <el-select
          v-model="value"
          placeholder="请选择导出的样式"
          style="width: 240px"
        >
          <el-option
            v-for="item in options"
            :key="item.value"
            :label="item.label"
            :value="item.value"
            @change="selectInputType"
          />
        </el-select>

        <el-button type="primary" @click="generation" round
          >生成创意画作</el-button
        >
      </div>
    </div>
    <div class="out-containter">
      <div class="demo-image__lazy">
        <el-image v-for="url in urls" :key="url" :src="url" lazy />
      </div>
    </div>
  </div>
</template>

<script>
import { defineComponent, ref } from "vue";
import { UploadFilled } from "@element-plus/icons-vue";
import { getTasks, getTaskInfo } from "../api/WanApi.js";
import { uuid } from "vue-uuid";
import ObsClient from "esdk-obs-browserjs/src/obs";

export default defineComponent({
  setup() {
    const imageUrl = ref("");
    const urls = ref([]);
    const value = ref("");

    const options = [
      {
        value: "0",
        label: "复古漫画",
      },
      {
        value: "1",
        label: "3D童话",
      },
      {
        value: "2",
        label: "二次元",
      },
      {
        value: "3",
        label: "小清新",
      },
      {
        value: "4",
        label: "未来科技",
      },
      {
        value: "5",
        label: "国画古风",
      },
      {
        value: "6",
        label: "将军百战",
      },
      {
        value: "7",
        label: "炫彩卡通",
      },
      {
        value: "8",
        label: "清雅国风",
      },
      {
        value: "9",
        label: "喜迎新年",
      },
    ];

    const getList = async () => {
      const tasks = await getTasks();
      console.log("页面获取到所有任务：", tasks);
      if (tasks.data) {
        tasks.data.forEach(async (e) => {
          if (e.status === "SUCCEEDED" && e.task_id) {
            console.log("获取任务：", e.task_id);
            const taskInfo = await getTaskInfo(e.task_id);
            if (taskInfo && taskInfo.output.task_status === "SUCCEEDED") {
              taskInfo.output.results.forEach((item) => {
                urls.value.push(item.url);
              });
            }
          }
        });
      }
    };

    getList();

    return {
      urls,
      value,
      options,
      imageUrl,
      file: undefined,
    };
  },
  components: {
    UploadFilled,
  },
  watch: {
    selectInputType(val) {
      const option = this.options.find((item) => item.value == val);
      this.value = option ? option.value : "";
    },
  },
  methods: {
    handleBeforeUpload(file) {
      console.log(file);
      let that = this;
      let fileExtension = "jpg";
      // 校检文件类型
      //   if (this.fileType) {
      //     if (file.name.lastIndexOf(".") > -1) {
      //       fileExtension = file.name.slice(file.name.lastIndexOf(".") + 1);
      //     }
      //     const isTypeOk = this.fileType.some((type) => {
      //       if (file.type.indexOf(type) > -1) return true;
      //       if (fileExtension && fileExtension.indexOf(type) > -1) return true;
      //       return false;
      //     });
      //     if (!isTypeOk) {
      //       this.msgError(
      //         `文件格式不正确, 请上传${this.fileType.join("/")}格式文件!`
      //       );
      //       return false;
      //     }
      //   }

      this.loading = this.$loading({
        lock: true,
        text: "上传中",
        background: "rgba(0, 0, 0, 0.7)",
      });
      let uuids = uuid.v1() + Date.now() + "." + fileExtension;

      // 创建ObsClient实例
      var obsClient = new ObsClient({
        access_key_id: "II3EI8YJCP9PWUBDLFSG",
        secret_access_key: "qqxHkkf9LIdOBOdGvavKBTDjFVM2bR08eWifE7bN",
        server: "http://10.88.65.57:8080",
      });

      console.log("file", file);
      console.log("file url", window.URL.createObjectURL(file));
      obsClient.putObject(
        {
          ContentType: "text/plain",
          Bucket: "huaweiyun/obs-dev-test-public",
          Key: "wanx/" + uuids, // 文件名   server是目录
          SourceFile: file, //文件本体
        },
        function (err, result) {
          if (err) {
            console.error("华为云上传出现异常-->" + err);
            that.handleUploadError();
          } else {
            console.log("华为云响应Status-->" + result.CommonMsg.Status);

            // OBS响应没有文件地址，需自行拼接   拼接格式： https:// +  桶名 + endPoint  +  /  + 上传的文件路径
            that.$emit(
              "input",
              "https://obs-dev-test-public.obs.cn-east-2.myhuaweicloud.com/server/" +
                uuids
            );
            that.loading.close();
          }
        }
      );

      return true;
    },
    generation() {
      console.log("选项：", this.value);
    },
  },
});
</script>

<style scoped>
.portraitRepaint-containter {
  /* display: flex; */
  height: 100vh;
}

.input-container {
  height: 20%;
  /* flex: 1;  */
  padding: 10px;
}

.input {
  margin-top: 2h;
  padding: 10px;
}

.out-container {
  height: 80%;
  padding: 10px;
  /* flex: 3;  */
}

.demo-image__lazy {
  height: 400px;
  /* overflow-y: auto; */
}

.demo-image__lazy .el-image {
  display: block;
  min-height: 200px;
  margin-bottom: 10px;
  padding: 10px;
}

.demo-image__lazy .el-image:last-child {
  margin-bottom: 0;
  padding: 10px;
}
</style>
